<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="仓库" prop="warehouseId">
            <WarehouseSelect v-model:wh-id="pd.queryParams.warehouseId" placeholder="请选择仓库" @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="盘点人" prop="userId">
            <el-input v-model="pd.queryParams.userId" placeholder="请输入盘点人" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="pd.queryParams.status" placeholder="请选择状态" clearable>
              <el-option v-for="dict in wms_stock_check_status" :key="dict.value" :label="dict.name" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:stockCheck:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()" v-hasPermi="['wms:stockCheck:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()" v-hasPermi="['wms:stockCheck:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:stockCheck:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.stockCheckList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope">
            <el-button link type="primary" icon="Finished" @click="handleExecOrder(scope.row)"
                       v-if="scope.row.status === '1'" v-hasPermi="['wms:order:edit']"> 执行
            </el-button>
            <el-button link type="primary" icon="check"
                       v-if="scope.row.status === '0'" v-hasPermi="['wms:order:edit']"> 完成
            </el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-if="scope.row.status === '1'" v-hasPermi="['wms:order:edit']"> 修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)"
                       v-if="scope.row.status === '1'" v-hasPermi="['wms:order:remove']">删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="盘点单" align="center" prop="name" />
        <el-table-column label="事务" align="center" prop="id">
          <template #default="scope">
            <el-link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['wms:stockCheck:edit']">
              {{ scope.row.id }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="仓库" align="center" prop="wareName" />
        <el-table-column label="盘点人" align="center" prop="userId" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="wms_stock_check_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="更新者" align="center" prop="updateBy" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />
      </el-table>

      <pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改测试主从对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="1000px" append-to-body>
      <el-form ref="stockCheckFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row :gutter="10" class="mb8">
          <el-form-item label="盘点单" prop="name">
            <el-input v-model="pd.form.name" placeholder="请输入盘点单名称" />
          </el-form-item>
          <el-form-item label="仓库" prop="warehouseId">
            <WarehouseSelect :disabled="pd.form.warehouseId" v-model:wh-id="pd.form.warehouseId" placeholder="请选择仓库" />
          </el-form-item>
          <el-form-item label="盘点人" prop="useId">
            <el-input v-model="pd.form.nickName" placeholder="请输入盘点人" />
          </el-form-item>
        </el-row>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button v-if="!pd.form.id" :icon="Plus" type="success" @click="submitForm">保存单据</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-if="pd.form.id" :icon="Delete" type="danger" @click="handleDelete(pd.form.id)">删除单据
          </el-button>
        </el-col>
        <el-col v-if="pd.form.id" :span="1.5">
          <el-button icon="Plus" type="success" @click="submitForm">修改单据</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Close" type="info" @click="cancel()">关闭</el-button>
        </el-col>
        <el-col :span="1.5">
          <StockSearch :isDisabled="true" :searchType="2" :isSingle="true" :params="{warehouseId:pd.form.warehouseId}"
                       title="库存查询" dataText="添加库存产品" @ok="lineAdd" />
        </el-col>
      </el-row>
      <el-table v-loading="pd.loading" :data="pd.form.line">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="产品名" width="150" align="center" prop="productName" />
        <el-table-column label="单位" width="120" align="center" prop="measureUnit" />
        <el-table-column label="批次号" width="100" align="center" prop="batchCode" />
        <el-table-column label="当前库存数量" width="120" align="center" prop="beforeQuantity" />
        <el-table-column label="将当前库存数量修改为" align="center" prop="checkQuantity">
          <template #default="scope">
            <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="scope.row.checkQuantity" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="delLine(scope.row)" v-hasPermi="['hrp:example:del']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="pd.lineTotal > 0" :total="pd.lineTotal" v-model:page="pd.queryLineParams.pageNum"
                  v-model:limit="pd.queryLineParams.pageSize" @pagination="getLineList"/>
    </el-dialog>
    <!-- 查看 -->
    <el-dialog :title="pd.inspectionDialog.title" v-model="pd.inspectionDialog.visible" width="1000">
      <el-descriptions>
        <el-descriptions-item label="单据名称">{{ pd.form.name }}</el-descriptions-item>
        <el-descriptions-item label="仓库">{{ pd.form.wareName }}</el-descriptions-item>
        <el-descriptions-item label="盘点人">{{ pd.form.nickName }}</el-descriptions-item>
      </el-descriptions>
      <el-table :data="pd.form.line" stripe style="width: 100%">
        <el-table-column label="产品名"  align="center" prop="productName" />
        <el-table-column label="单位"  align="center" prop="measureUnit" />
        <el-table-column label="批次号"  align="center" prop="batchCode" />
        <el-table-column label="当前库存数量" align="center" prop="beforeQuantity" />
        <el-table-column label="将当前库存数量修改为" align="center" prop="checkQuantity"/>
      </el-table>
      <pagination class="print-hidden" v-show="pd.lineTotal>0" :total="pd.lineTotal" v-model:page="pd.queryLineParams.pageNum"
                  v-model:limit="pd.queryLineParams.pageSize" @pagination="getLineList"/>
      <el-col :span="1.5">
        <el-button class="print-hidden" style="float: inherit" type="primary" @click="print">打印</el-button>
      </el-col>
    </el-dialog>
  </div>
</template>

<script setup name="StockCheck" lang="ts">
import {
  addStockCheck,
  delStockCheck,
  delStockCheckLine,
  listStockCheck,
  listStockCheckLine,
  StockCheckLineVO,
  StockCheckVO,
  updateStockCheck
} from '@/views/wms/stockCheck/api';
import WarehouseSelect from "@/views/wms/warehouse/select.vue";
import StockSearch from "@/views/wms/stock/search.vue";
import {send, setStock, StockVO} from "@/views/wms/stock/api";
import {Delete, Plus} from "@element-plus/icons-vue";
import getInfo from "@/store/modules/user";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wms_stock_check_status } = toRefs<any>(proxy?.useDict('wms_stock_check_status'));
const logUser = getInfo();

const queryFormRef = ref<ElFormInstance>();
const stockCheckFormRef = ref<ElFormInstance>();

const pd = reactive({
  stockCheckList: <StockCheckVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  selectVO: <StockCheckVO[]>([]),
  single: true,
  multiple: true,
  total: 0,
  lineTotal: 0,
  stockList: <StockVO[]>([]),
  form: <StockCheckVO>{},
  queryParams: <StockCheckVO>{
    pageNum: 1,
    pageSize: 10,
    warehouseId: undefined,
    userId: undefined,
    status: undefined,
    params: {
    }
  },
  queryLineParams: <StockCheckLineVO>{
    pageNum: 1,
    pageSize: 10,
    id: undefined
  },
  stockQueryParams: <StockVO>{
    pageNum: 1,
    pageSize: 10,
    productId: undefined,
    measureUnit: undefined,
    batchCode: undefined,
    warehouseId: undefined,
    areaId: undefined,
    supplierId: undefined,
    manufacturerId: undefined,
    quantity: undefined,
    purchasePrice: undefined,
    expireDate: undefined,
    params: {
    }
  },
  rules: <ElFormRules>{
    name: [
      { required: true, message: "盘点单名称不能为空", trigger: "blur" }
    ],
    warehouseId: [
      { required: true, message: "仓库不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "盘点人不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  },
  dialog: <DialogOption>{
    visible: false,
    title: '添加库存盘点'
  },
  inspectionDialog: <DialogOption>{
    visible: false,
    title: '采购订单-详情'
  },
});

// const { queryParams, form, rules } = toRefs(data);

/** 查询库存盘点列表 */
async function getList() {
  pd.loading = true;
  const res = await listStockCheck(pd.queryParams);
  pd.stockCheckList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = {};
  stockCheckFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: StockCheckVO[]) {
  pd.selectVO = selection;
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.visible = true;
  pd.dialog.title = "新增库存盘点";
  pd.form.line = [];
  pd.form.userId = logUser.userId;
  pd.form.nickName = logUser.nickname;
}
/** 修改按钮操作 */
async function handleUpdate(row?: StockCheckVO) {
  reset();
  const data = row || pd.selectVO[0]
  Object.assign(pd.form, data);
  if (row?.status == "0"){
    pd.inspectionDialog.visible = true;
    pd.inspectionDialog.title = '零售订单-详情';
  }else{
    pd.dialog.visible = true;
    pd.dialog.title = "修改库存盘点";
  }
  await getLineList();
}

/** 提交按钮 */
function submitForm() {
  stockCheckFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateStockCheck(pd.form).finally(() =>  pd.buttonLoading = false);
        proxy?.$modal.msgSuccess("修改成功");
      } else {
        pd.form.status = '1';
        await addStockCheck(pd.form).finally(() =>  pd.buttonLoading = false);
        proxy?.$modal.msgSuccess("添加成功");
      }
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(id?: string | number) {
  const _ids = id ? id : pd.selectVO.map(v => v.id);
  await proxy?.$modal.confirm('是否确认删除库存盘点编号为"' + _ids + '"及其子表的数据项？').finally(() => pd.loading = false);
  await delStockCheck(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/stockCheck/export', {
    ...pd.queryParams
  }, `stockCheck_${new Date().getTime()}.xlsx`)
}


/** 新增行按钮操作 */
async function lineAdd(vo: StockVO[]) {
  let line: StockCheckLineVO = {pageNum: 0, pageSize: 0};
  vo.forEach((v, i, a) => {
    line = <StockCheckLineVO>{}
    line.productId = v.productId;
    line.productName = v.productName;
    line.measureUnit = v.measureUnit;
    line.beforeQuantity = v.quantity;
    line.batchCode = v.batchCode;
    line.warehouseId = v.warehouseId;
    line.supplierId = v.id ? parseInt(String(v.supplierId)):undefined;
    line.id = pd.form.id;
    if (!pd.form.line!.find(item => item.productId === line.productId && item.batchCode === line.batchCode)){
      pd.form.line!.push(line);
    }
    pd.form.warehouseId = v.warehouseId;
  });
}
watch(()=>pd.form.line,(value)=>{
  if (value != undefined && value.length == 0){
    pd.form.warehouseId = undefined;
  }
},{deep:true})

/** 删除子表操作 */
async function delLine(row: StockCheckLineVO) {
  if (row.lineId === undefined) {
    const index = pd.form.line!.indexOf(row);
    pd.form.line!.splice(index, 1);
    return;
  }
  proxy?.$modal.confirm('是否确认删除 子单号为:"' + row.lineId + '"的数据项？').then(function () {
    return delStockCheckLine(row.lineId!);
  }).then(() => {
    const index = pd.form.line!.indexOf(row);
    pd.form.line!.splice(index, 1);
    proxy.$modal.msgSuccess("删除成功");
    // getLineList();
  }).catch(() => {
  });
}
/** 查询子列表 */
async function getLineList() {
  pd.loading = true;
  pd.queryLineParams.id = pd.form.id;
  await listStockCheckLine(pd.queryLineParams).then(res => {
    pd.form.line = res.rows;
    pd.lineTotal = res.total;
    pd.loading = false;
  });
}

/** 库存盘点 发送  */
async function handleSendOrder(row: StockCheckVO){
  if (row.status != "1" ){
    return;
  }
    await proxy?.$modal.confirm('确认要发送"' + row.id + '" 订单吗?');
    row.status="3";
    await send(row);
    proxy?.$modal.msgSuccess(row.id + "成功");
}
/** 库存盘点 执行  */
async function handleExecOrder(vo: StockCheckVO) {
  await proxy?.$modal.confirm('是否执行"' + vo!.id + '"的数据？');
  await setStock(vo).then(res => {
    resetQuery();
  });
}
onMounted(() => {
  getList();
});
</script>
